<template>
  <div class="login">
    <h1 style="text-align:center;font-size:18px;margin-top:20px">欢迎来到开卖啦后台管理系统</h1>
    <div class="login-content">
      <el-form 
      :rules="rules"
      :model="form"
      ref="form"
      >
        <h1>登录</h1>
        <el-form-item label="用户名" prop="username">
           <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
           <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {mapActions} from 'vuex'
export default {
    name:'login',
    data() {
      return {
        form:{
          username:'',
          password:''
        },
        rules:{
          username:[
            {required:true,message:"请输入用户名",trigger:"blur"},
            {min:3,max:20,mssage:"用户名长度为3~20位",trigger:"blur"},
          ],
          password:[
            {required:true,message:"请输入密码",trigger:"blur"},
            {min:3,max:20,message:"用户名长度为3~20位",trigger:"blur"},
          ]
        }
      }
    },
    methods: {
      submitForm(){
        console.log("登录！")
        this.$refs['form'].validate( valid =>{  //DOM对象如果通过了校验规则，则执行validate方法
          if (valid) {                     //此方法返回的调用函数callback(valid),可以使用箭头函数获取valid值并且使用
            //登录的数据，通常放在store里面
            this.userLogin(this.form)
            .then((result)=>{
              if (result.data.code === 200) {

                console.log(this.$route)
                let target = this.$route.query.redirect
                console.log(target)
                if (!target) {
                  target = "/home"
                }
                this.$router.push(target)
              }
              else if(result.data.msg === "用户信息不存在"){
                alert('用户信息不存在')
              }
              else{
                alert('用户名密码错误')
              }
            }).catch((err)=>{
              console.log(err)
            });
          }
        })
      },
      ...mapActions(['userLogin'])
    },
}
</script>

<style scoped>
.login-content{
  width: 500px;
  margin: 0 auto;
  margin-top: 100px;
  border: solid 1px #aaa;
  padding: 20px;
  box-shadow:  0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px
}
.login-content h1{
  text-align: center;
  font-size: 25px;
  font-weight: 500;
}
</style>